from fastapi import APIRouter, Depends, HTTPException, Query, Path, Body, status
from fastapi.responses import JSONResponse
from typing import List, Optional, Dict, Any, Union
from datetime import datetime
from uuid import UUID

from server.schemas.server import (
    ServerCreate, ServerUpdate, ServerResponse, ServerBriefResponse,
    ServerStatusUpdate, ServerStatisticsResponse, ServerLogResponse,
    ServerBatchOperation, ServerModBatchOperation, ServerModLoadOrderUpdate,
    ServerConfigBatchUpdate, ServerSearchResponse, ServerBackupCreate,
    ServerBackupResponse, ServerModCreate, ServerModResponse, ServerConfigCreate,
    ServerConfigResponse
)
from server.schemas.common import PageResponse, SuccessResponse
from server.services.server_service import ServerService
from server.services.auth_service import AuthService
from server.api.v1.dependencies import get_server_service, get_auth_service
from server.core.security import get_current_user
from server.schemas.user import UserResponse
from server.core.exceptions import NotFoundException, PermissionDeniedException,
    ResourceConflictException, OperationFailedException

router = APIRouter(prefix="/servers", tags=["servers"])

@router.post(
    "/",
    response_model=ServerResponse,
    status_code=status.HTTP_201_CREATED,
    description="创建新的幻兽帕鲁服务器"
)
async def create_server(
    server: ServerCreate = Body(..., description="服务器创建信息"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    # 检查权限
    if not await auth_service.has_permission(current_user.id, "server:create"):
        raise PermissionDeniedException("没有创建服务器的权限")

    try:
        # 检查名称唯一性
        if await server_service.get_server_by_name(server.name):
            raise ResourceConflictException(f"名称为'{server.name}'的服务器已存在")

        # 创建服务器
        new_server = await server_service.create_server(
            server, creator_id=current_user.id
        )
        return new_server
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"创建服务器失败: {str(e)}"
        )

@router.get(
    "/",
    response_model=ServerSearchResponse,
    description="获取服务器列表，支持分页、搜索和筛选"
)
async def get_servers(
    name: Optional[str] = Query(None, description="按名称搜索"),
    status: Optional[str] = Query(None, description="按状态筛选"),
    server_type: Optional[str] = Query(None, description="按服务器类型筛选"),
    is_public: Optional[bool] = Query(None, description="是否公开服务器"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页条数"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    # 管理员可以查看所有服务器，普通用户只能查看自己创建的或公开的服务器
    if await auth_service.has_permission(current_user.id, "server:view_all"):
        user_id = None
    else:
        user_id = current_user.id

    servers, total = await server_service.get_servers(
        name=name,
        status=status,
        server_type=server_type,
        is_public=is_public,
        user_id=user_id,
        page=page,
        page_size=page_size
    )

    total_pages = (total + page_size - 1) // page_size
    return {
        "servers": servers,
        "total": total,
        "page": page,
        "page_size": page_size,
        "total_pages": total_pages
    }

@router.get(
    "/{server_id}",
    response_model=ServerResponse,
    description="通过ID获取服务器详细信息"
)
async def get_server(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限：管理员可以查看所有服务器，用户只能查看自己创建的或公开的服务器
        if not await auth_service.has_permission(current_user.id, "server:view_all"):
            if server.created_by != current_user.id and not server.is_public:
                raise PermissionDeniedException("没有查看该服务器的权限")

        return server
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))

@router.put(
    "/{server_id}",
    response_model=ServerResponse,
    description="更新服务器信息"
)
async def update_server(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    server_update: ServerUpdate = Body(..., description="服务器更新信息"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限：管理员可以更新所有服务器，用户只能更新自己创建的服务器
        if not await auth_service.has_permission(current_user.id, "server:edit_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有更新该服务器的权限")

        # 如果修改了名称，检查唯一性
        if server_update.name and server_update.name != server.name:
            existing_server = await server_service.get_server_by_name(server_update.name)
            if existing_server and existing_server.id != server_id:
                raise ResourceConflictException(f"名称为'{server_update.name}'的服务器已存在")

        # 更新服务器
        updated_server = await server_service.update_server(server_id, server_update)
        return updated_server
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except ResourceConflictException as e:
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))

@router.delete(
    "/{server_id}",
    response_model=SuccessResponse,
    status_code=status.HTTP_200_OK,
    description="删除服务器"
)
async def delete_server(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限：只有管理员或服务器创建者可以删除服务器
        if not await auth_service.has_permission(current_user.id, "server:delete_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有删除该服务器的权限")

        # 如果服务器正在运行，先停止
        if server.status == "running":
            await server_service.stop_server(server_id, current_user.id)

        # 删除服务器
        await server_service.delete_server(server_id)
        return SuccessResponse(success=True, message=f"ID为{server_id}的服务器已成功删除")
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

@router.post(
    "/{server_id}/start",
    response_model=ServerStatusUpdate,
    description="启动服务器"
)
async def start_server(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:control_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有启动该服务器的权限")

        # 检查服务器状态
        if server.status == "running":
            raise OperationFailedException("服务器已经在运行中")

        # 启动服务器
        result = await server_service.start_server(server_id, current_user.id)
        return result
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))

@router.post(
    "/{server_id}/stop",
    response_model=ServerStatusUpdate,
    description="停止服务器"
)
async def stop_server(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    force: bool = Query(False, description="是否强制停止"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:control_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有停止该服务器的权限")

        # 检查服务器状态
        if server.status == "stopped":
            raise OperationFailedException("服务器已经处于停止状态")

        # 停止服务器
        result = await server_service.stop_server(server_id, current_user.id, force=force)
        return result
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))

@router.post(
    "/{server_id}/restart",
    response_model=ServerStatusUpdate,
    description="重启服务器"
)
async def restart_server(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    force: bool = Query(False, description="是否强制重启"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:control_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有重启该服务器的权限")

        # 检查服务器状态
        if server.status == "stopped":
            raise OperationFailedException("服务器当前处于停止状态，请先启动服务器")

        # 重启服务器
        result = await server_service.restart_server(server_id, current_user.id, force=force)
        return result
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))

@router.post(
    "/batch-operation",
    response_model=SuccessResponse,
    description="服务器批量操作"
)
async def batch_operation(
    operation: ServerBatchOperation = Body(..., description="批量操作信息"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    # 检查权限：批量操作需要管理员权限
    if not await auth_service.has_permission(current_user.id, "server:batch_operation"):
        raise PermissionDeniedException("没有执行批量操作的权限")

    try:
        # 执行批量操作
        result = await server_service.batch_operation(
            operation.server_ids, operation.operation, operation.params, current_user.id
        )
        return SuccessResponse(
            success=True,
            message=f"成功对{len(operation.server_ids)}个服务器执行{operation.operation}操作",
            data=result
        )
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

@router.get(
    "/statistics",
    response_model=ServerStatisticsResponse,
    description="获取服务器统计信息"
)
async def get_server_statistics(
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    # 检查权限：只有管理员可以查看统计信息
    if not await auth_service.has_permission(current_user.id, "server:statistics"):
        raise PermissionDeniedException("没有查看服务器统计信息的权限")

    try:
        statistics = await server_service.get_server_statistics()
        return statistics
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"获取服务器统计信息失败: {str(e)}"
        )

@router.get(
    "/{server_id}/logs",
    response_model=ServerLogResponse,
    description="获取服务器日志"
)
async def get_server_logs(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    log_type: Optional[str] = Query(None, description="日志类型过滤"),
    log_level: Optional[str] = Query(None, description="日志级别过滤"),
    start_time: Optional[datetime] = Query(None, description="开始时间"),
    end_time: Optional[datetime] = Query(None, description="结束时间"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页条数"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:view_logs_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有查看该服务器日志的权限")

        # 获取日志
        logs, total = await server_service.get_server_logs(
            server_id, log_type, log_level, start_time, end_time, page, page_size
        )

        total_pages = (total + page_size - 1) // page_size
        return ServerLogResponse(
            server_id=server_id,
            logs=logs,
            total=total,
            page=page,
            page_size=page_size,
            total_pages=total_pages
        )
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))

@router.post(
    "/{server_id}/backups",
    response_model=ServerBackupResponse,
    status_code=status.HTTP_201_CREATED,
    description="创建服务器备份"
)
async def create_server_backup(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    backup_info: ServerBackupCreate = Body(..., description="备份信息"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:backup_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有创建该服务器备份的权限")

        # 创建备份
        backup = await server_service.create_backup(
            server_id, backup_info, current_user.id
        )
        return backup
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

@router.get(
    "/{server_id}/backups",
    response_model=PageResponse[ServerBackupResponse],
    description="获取服务器备份列表"
)
async def get_server_backups(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=50, description="每页条数"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:backup_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有查看该服务器备份的权限")

        # 获取备份列表
        backups, total = await server_service.get_server_backups(
            server_id, page, page_size
        )

        total_pages = (total + page_size - 1) // page_size
        return PageResponse(
            items=backups,
            total=total,
            page=page,
            page_size=page_size,
            total_pages=total_pages
        )
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))

@router.post(
    "/{server_id}/mods",
    response_model=ServerModResponse,
    status_code=status.HTTP_201_CREATED,
    description="安装服务器模组"
)
async def install_server_mod(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    mod_info: ServerModCreate = Body(..., description="模组信息"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:mod_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有为该服务器安装模组的权限")

        # 检查模组是否已安装
        existing_mod = await server_service.get_server_mod_by_id(
            server_id, mod_info.mod_id
        )
        if existing_mod:
            raise ResourceConflictException(f"模组{mod_info.mod_id}已安装在该服务器上")

        # 安装模组
        mod = await server_service.install_mod(
            server_id, mod_info, current_user.id
        )
        return mod
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except ResourceConflictException as e:
        raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

@router.post(
    "/{server_id}/mods/batch-operation",
    response_model=SuccessResponse,
    description="服务器模组批量操作"
)
async def batch_mod_operation(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    operation: ServerModBatchOperation = Body(..., description="模组批量操作信息"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:mod_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有执行模组批量操作的权限")

        # 执行批量操作
        result = await server_service.batch_mod_operation(
            server_id, operation.mod_ids, operation.operation, current_user.id
        )
        return SuccessResponse(
            success=True,
            message=f"成功对{len(operation.mod_ids)}个模组执行{operation.operation}操作",
            data=result
        )
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

@router.put(
    "/{server_id}/mods/load-order",
    response_model=SuccessResponse,
    description="更新模组加载顺序"
)
async def update_mod_load_order(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    load_order: ServerModLoadOrderUpdate = Body(..., description="模组加载顺序信息"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:mod_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有更新模组加载顺序的权限")

        # 更新加载顺序
        await server_service.update_mod_load_order(
            server_id, load_order.mod_ids, current_user.id
        )
        return SuccessResponse(
            success=True,
            message="成功更新模组加载顺序"
        )
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

@router.post(
    "/{server_id}/configs",
    response_model=ServerConfigResponse,
    status_code=status.HTTP_201_CREATED,
    description="添加服务器配置"
)
async def add_server_config(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    config: ServerConfigCreate = Body(..., description="配置信息"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:config_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有添加服务器配置的权限")

        # 添加配置
        config = await server_service.add_config(
            server_id, config, current_user.id
        )
        return config
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

@router.post(
    "/{server_id}/configs/batch-update",
    response_model=SuccessResponse,
    description="批量更新服务器配置"
)
async def batch_update_config(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    configs: ServerConfigBatchUpdate = Body(..., description="配置信息"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:config_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有批量更新服务器配置的权限")

        # 批量更新配置
        updated_count = await server_service.batch_update_configs(
            server_id, configs.configs, current_user.id
        )
        return SuccessResponse(
            success=True,
            message=f"成功更新{updated_count}项服务器配置"
        )
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

@router.get(
    "/search",
    response_model=ServerSearchResponse,
    description="搜索服务器"
)
async def search_servers(
    query: str = Query(..., description="搜索关键词"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=50, description="每页条数"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service)
):
    try:
        # 普通用户只能搜索自己创建的或公开的服务器
        servers, total = await server_service.search_servers(
            query, current_user.id, page, page_size
        )

        total_pages = (total + page_size - 1) // page_size
        return ServerSearchResponse(
            servers=servers,
            total=total,
            page=page,
            page_size=page_size,
            total_pages=total_pages
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"搜索服务器失败: {str(e)}"
        )

@router.post(
    "/{server_id}/validate",
    response_model=SuccessResponse,
    description="验证服务器配置"
)
async def validate_server_config(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:validate_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有验证服务器配置的权限")

        # 验证配置
        validation_result = await server_service.validate_server_config(server_id)
        return SuccessResponse(
            success=validation_result["valid"],
            message=validation_result["message"],
            data=validation_result["details"]
        )
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))

@router.post(
    "/{server_id}/install",
    response_model=SuccessResponse,
    description="安装服务器文件"
)
async def install_server_files(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    validate: bool = Query(True, description="是否验证文件完整性"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:install_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有安装服务器文件的权限")

        # 检查服务器状态
        if server.status != "stopped":
            raise OperationFailedException("只能在服务器停止状态下安装文件")

        # 安装服务器文件
        result = await server_service.install_server_files(
            server_id, validate=validate, user_id=current_user.id
        )
        return SuccessResponse(
            success=True,
            message=f"服务器文件安装{result['status']}",
            data=result
        )
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"服务器文件安装失败: {str(e)}"
        )

@router.post(
    "/{server_id}/update",
    response_model=SuccessResponse,
    description="更新服务器文件"
)
async def update_server_files(
    server_id: int = Path(..., ge=1, description="服务器ID"),
    validate: bool = Query(True, description="是否验证文件完整性"),
    current_user: UserResponse = Depends(get_current_user),
    server_service: ServerService = Depends(get_server_service),
    auth_service: AuthService = Depends(get_auth_service)
):
    try:
        server = await server_service.get_server_by_id(server_id)
        if not server:
            raise NotFoundException(f"ID为{server_id}的服务器不存在")

        # 检查权限
        if not await auth_service.has_permission(current_user.id, "server:update_all"):
            if server.created_by != current_user.id:
                raise PermissionDeniedException("没有更新服务器文件的权限")

        # 检查服务器状态
        if server.status != "stopped":
            raise OperationFailedException("只能在服务器停止状态下更新文件")

        # 更新服务器文件
        result = await server_service.update_server_files(
            server_id, validate=validate, user_id=current_user.id
        )
        return SuccessResponse(
            success=True,
            message=f"服务器文件更新{result['status']}",
            data=result
        )
    except NotFoundException as e:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
    except PermissionDeniedException as e:
        raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=str(e))
    except OperationFailedException as e:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail=f"服务器文件更新失败: {str(e)}"
        )